package com.cipe.cmrs.service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import javax.xml.rpc.holders.ByteArrayHolder;
import javax.xml.rpc.holders.StringHolder;
import javax.xml.soap.SOAPException;

import org.apache.axis.message.SOAPHeaderElement;
import org.apache.commons.httpclient.auth.AuthPolicy;
import org.springframework.stereotype.Service;

import com.microsoft.schemas.sqlserver._2005._06._30.reporting.reportingservices.ExecutionInfo;
import com.microsoft.schemas.sqlserver._2005._06._30.reporting.reportingservices.ParameterValue;
import com.microsoft.schemas.sqlserver._2005._06._30.reporting.reportingservices.ReportExecutionServiceLocator;
import com.microsoft.schemas.sqlserver._2005._06._30.reporting.reportingservices.ReportExecutionServiceSoapStub;
import com.microsoft.schemas.sqlserver._2005._06._30.reporting.reportingservices.holders.ArrayOfStringHolder;
import com.microsoft.schemas.sqlserver._2005._06._30.reporting.reportingservices.holders.ArrayOfWarningHolder;

/**
 * 
 * @author Shishir Lamichhane
 *
 */
@Service
public class SsrsReportService {
	
	/**
	 * This method returns the inputstream of the PDF format to display.
	 * @param parameters The query parameters to set for the SSRS report
	 * @param reportName The report name to request
	 * @return
	 */
	public InputStream getResponsePDF(ParameterValue[] parameters, String reportName) {
		
		  ReportExecutionServiceSoapStub service = getService();
		  InputStream is = null;
	  
		  try {
			  
			   AuthPolicy.registerAuthScheme(AuthPolicy.NTLM, com.cipe.cmrs.util.JCIFS_NTLMScheme.class);
			   ExecutionInfo info = service.loadReport(reportName, null); //Load report
			   setExecutionId(service, info.getExecutionID()); //You must set the session id before continuing
			   service.setExecutionParameters(parameters, "en-us"); //Set report parameters
			   
			   String format = "PDF"; //Valid options are HTML4.0, MHTML, EXCEL, CSV, PDF, etc
			   String deviceInfo = "<DeviceInfo><Toolbar>False</Toolbar><HTMLFragment>True</HTMLFragment></DeviceInfo>"; //Only generate an HTML fragment
			   ByteArrayHolder result = new ByteArrayHolder();
			   StringHolder extension = new StringHolder();
			   StringHolder mimeType = new StringHolder();
			   StringHolder encoding = new StringHolder();
			   ArrayOfWarningHolder warnings = new ArrayOfWarningHolder();
			   ArrayOfStringHolder streamIDs = new ArrayOfStringHolder();   
			   service.render(format, deviceInfo, result, extension, mimeType, encoding, warnings, streamIDs); //Render report to HTML
			   
			   is = new ByteArrayInputStream(result.value);

		  }
		  catch (Exception e) {
			  e.printStackTrace();
		  }
		  return is;
	  
		}
 
	public static void setExecutionId(ReportExecutionServiceSoapStub service, String id) throws SOAPException {
	  SOAPHeaderElement sessionHeader = new SOAPHeaderElement("http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", "ExecutionHeader");
	  sessionHeader.addChildElement("ExecutionID").addTextNode(id);
	  service.setHeader(sessionHeader);
	}
 
	public static ReportExecutionServiceSoapStub getService() {
	  try
	  {
		  String endpoint = "http://localhost/ReportServer/ReportExecution2005.asmx?wsdl";   
		  ReportExecutionServiceSoapStub service = (ReportExecutionServiceSoapStub)new ReportExecutionServiceLocator(getEngineConfiguration()).getReportExecutionServiceSoap(new URL(endpoint));
		  service.setUsername("server9\\AdminMW");
		  service.setPassword("ihrp-10%more");
		 
		  return service;
	  }
	  catch (Exception e) {
		  e.printStackTrace();
	  }
  
	  return null;
	}
 
	public static org.apache.axis.EngineConfiguration getEngineConfiguration() {
		
	  java.lang.StringBuffer sb = new java.lang.StringBuffer();
	  
	  sb.append("<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\r\n");
	  sb.append("<deployment name=\"defaultClientConfig\"\r\n");
	  sb.append("xmlns=\"http://xml.apache.org/axis/wsdd/\"\r\n");
	  sb.append("xmlns:java=\"http://xml.apache.org/axis/wsdd/providers/java\">\r\n");
	  sb.append("<globalConfiguration>\r\n");
	  sb.append("<parameter name=\"disablePrettyXML\" value=\"true\"/>\r\n");
	  sb.append("<parameter name=\"enableNamespacePrefixOptimization\" value=\"true\"/>\r\n");
	  sb.append("</globalConfiguration>\r\n");
	  sb.append("<transport name=\"http\" pivot=\"java:org.apache.axis.transport.http.CommonsHTTPSender\"/>\r\n");
	  sb.append("<transport name=\"local\" pivot=\"java:org.apache.axis.transport.local.LocalSender\"/>\r\n");
	  sb.append("<transport name=\"java\" pivot=\"java:org.apache.axis.transport.java.JavaSender\"/>\r\n");
	  sb.append("</deployment>\r\n");
	  
	  return new org.apache.axis.configuration.XMLStringProvider(sb.toString());
	}
}